/**
 * Created by zhaizy on 2015/3/17.
 */

angular.module('myservice', ['base64', 'constantService'])


.provider("intent", function() {



    this.$get = function() {
        return {

        }
    }

})


//MSM_HEADER CmdType=FHBX;CmdModule=ORDER;CmdId=Search;CmdVer=1.0.0;ToKen=
//MSM_PARAM uuid=B88C62ADF49D4343AA76829209CCD614;orderStatus=NTP;startDate=2015-02-18;max=10;offset=0
.provider("zzbHttp", function($base64) {

    //获取请求头
    var getHeader = function(header) {
        //return "CmdType=" + CmdType + ";CmdModule=" + CmdModule + ";CmdId=" + CmdId
        var headers = "";
        for (var key in header) {
            console.log("key value:" + key + "-" + header[key]);
            headers = headers + key + "=" + header[key] + ";";
        }

        console.log("headers :" + headers);
        return headers;
    };

    //获取请求的参数
    var getParam = function(ParamObject) {
        var params = "";
        for (var key in ParamObject) {
            console.log("key value:" + key + "-" + ParamObject[key]);
            params = params + key + "=" + ParamObject[key] + ";";
        }

        console.log("params :" + params);
        return params;
    };

    function make_base_auth(user, password) {
        var tok = user + ':' + password;
        var hash = $base64.encode(tok);
        return "Basic " + hash;
    }

    this.$get = function($http, $q, zzbLocalCache, $ionicLoading, PreferenceKey) {
        return {
            login: function(headers, params, loadingTips) {
                var defered = $q.defer();
                var loginUrl = "https://10.68.3.250:443/online/session";
                $ionicLoading.show({
                    template: !loadingTips ? 'Loading...' : loadingTips
                });

                var auth = make_base_auth(headers.username, headers.password);
                $http({
                    url: loginUrl,
                    method: "post",
                    headers: {
                        Authorization: auth
                    },
                    params: {},
                    data: {
                        "needLicense": false
                    }
                }).success(function(result) {
                    //{
                    //    "state": true,
                    //    "message": "用户验证通过",
                    //    "entity": {
                    //    "uid": "B88C62ADF49D4343AA76829209CCD614",
                    //        "sid": "8912303151133585225",
                    //        "token": "MTQyNzA4MTYzOA==bW9ib2ba0c811d302bd6dbc55a83fb1e6030fc47b8eb",
                    //        "terminal": "mob"
                    //}
                    //}
                    console.log("login:" + JSON.stringify(result));
                    if (result.state) {
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_USER_NAME, headers.username);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_PASSWORD, headers.password);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_UID, result.entity.uid);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_SID, result.entity.sid);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_TOKEN, result.entity.token);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_TERMINAL, result.entity.terminal);
                    }
                    $ionicLoading.hide();
                    defered.resolve(result.state)
                }).error(function(error) {
                    $ionicLoading.hide();
                    defered.reject(error);
                });

                return defered.promise;
            },

            //    需要验证header中的uid，sid，token，terminal信息，
            //
            //https://ip/jrdt/online/agentinfo/手机号(工号)/token
            //{
            //    "imei": "手机imei号码",
            //    "plate": "系统类型",
            //    "brand": "品牌"
            //}
            postHttps: function(url, params, loadingTips) {
                var defered = $q.defer();
                var dtUrl = "https://10.68.3.250:443/jrdt/online/" + url;
                $ionicLoading.show({
                    template: !loadingTips ? 'Loading...' : loadingTips
                });
                var uid = zzbLocalCache.get(PreferenceKey.PRE_KEY_UID);
                var sid = zzbLocalCache.get(PreferenceKey.PRE_KEY_SID);
                var token = zzbLocalCache.get(PreferenceKey.PRE_KEY_TOKEN);
                var terminal = zzbLocalCache.get(PreferenceKey.PRE_KEY_TERMINAL);
                $http({
                    url: dtUrl,
                    method: "post",
                    headers: {
                        uid: uid,
                        sid: sid,
                        token: token,
                        terminal: terminal
                    },
                    data: params
                }).success(function(result) {
                    $ionicLoading.hide();
                    defered.resolve(result)
                }).error(function(error) {
                    $ionicLoading.hide();
                    defered.reject(error);
                });

                return defered.promise;
            },

            getAgentInfo: function() {
                var phone = zzbLocalCache.get(PreferenceKey.PRE_KEY_UID);
                var url = "agentinfo/" + phone + "/" + zzbLocalCache.get(PreferenceKey.PRE_KEY_TOKEN);
                var defered = $q.defer();
                this.postHttps(url, {
                    imei: "00000000",
                    plate: "OS_ANDROID",
                    brand: "ionic"
                }, "获取个人信息").then(function(result) {
                    console.log("@@##then 获取个人信息");
                    defered.resolve(result);
                    if (result.state) {
                        var entity = result.entity;
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_EMPLOYEENUMBER, entity.Attributes.employeeNumber);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_FULL_NAME, entity.Attributes.fullName);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_MOBILE, entity.Attributes.mobile);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_EID, entity.Attributes.eid);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_AGENT_ID, entity.agentid);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_PLATFORM, entity.org.platform);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_BUSINESSOFFICE, entity.org.businessOffice);
                        zzbLocalCache.put(PreferenceKey.PRE_KEY_BUSINESSOFFICE_NAME, entity.org.businessOfficeName);
                        zzbLocalCache.put(PreferenceKey.PRE_ZONE_ID, entity.org.orgCityId);

                    }

                }, function(error) {
                    console.log("@@##then 获取个人信息 error");
                    defered.resolve(error);
                });
                return defered.promise;
            },

            post: function(header, params, loadingTips) {
                var defered = $q.defer();
                var zzbUrl = zzbLocalCache.get("custom");
                $ionicLoading.show({
                    template: !loadingTips ? 'Loading...' : loadingTips
                });

                $http({
                    url: zzbUrl,
                    method: "post",
                    params: {
                        MSM_HEADER: getHeader(header),
                        MSM_PARAM: getParam(params)
                    }
                }).success(function(result) {
                    $ionicLoading.hide();
                    defered.resolve(result)
                }).error(function(error) {
                    $ionicLoading.hide();
                    defered.reject(error);
                });
                console.log("the zzbUrl:" + zzbUrl);

                return defered.promise;
            }
        }
    };
})

//本地缓存 存在设备上
.provider("zzbLocalCache", function() {
    var cache = {};

    this.$get = function() {
        return {
            get: function(key) {
                var value = cache[key];
                if (!value) {
                    value = localStorage.getItem(key);
                }
                return value;
            },
            put: function(key, value) {
                cache[key] = value;
                localStorage.setItem(key, value);
            }
        }
    }


})

.factory("dialogService", function($ionicPopup, $q) {
    var service = {};

    service.showSelectDialog = function(scope, title, items) {
        var deffered = $q.defer();
        scope.item = {};
        scope.items = items;
        var myPopup = $ionicPopup.show({
            templateUrl: "templates/component/SingleSelectDialog.html",
            title: title,
            subTitle: '',
            scope: scope,
            buttons: [{
                text: '取消',
                onTap: function() {
                    deffered.reject("取消");
                }
            }, {
                text: '<b>确定</b>',
                type: 'button-positive',
                onTap: function() {
                    deffered.resolve(scope.items.item.value);
                }
            }]
        });
        myPopup.then(function(res) {
            console.log('Tapped!', res);
        });

        return deffered.promise;
    }

    service.showDialog = function() {
        alert("弹了");
    }

    return service;

})
